<?php
/**
 * Created by PhpStorm.
 * User: stiff
 * Date: 24/11/17
 * Time: 上午10:31
 */

namespace app\home\controller;

use think\Controller;
use Yunpian\Sdk\YunpianClient;
use app\home\model\SmsCode;
use app\home\model\WechatUser;
use think\Cookie;
use think\Config;

class Sms extends Controller
{
    public function _initialize()
    {
        Cookie::init(Config::get('cookie'));
    }

    static $ACTIVETIME = 300;// 验证码有效时间(秒)
    static $INTERVAL = 90;// 验证码间隔时间(秒)

    /**
     * 云片短信验证码
     */
    public function register()
    {
        if (IS_POST) {
            $data = input('post.');
            $checkRes = $this->checkParam($data); //检查参数 防止恶意调用 重复注册
            if ($checkRes) {
                $this->error($checkRes);
            }
            $rand = rand(1000, 9999); // 生成随机四位二维码

            $clnt = YunpianClient::create(Config('sms_apikey'));
            $param = [
                YunpianClient::MOBILE => $data['mobile'],
                YunpianClient::TEXT => '【富春硅谷】您的验证码是' . $rand . '。如非本人操作，请忽略本短信',
            ];
            $res = $clnt->sms()->single_send($param); //发送验证码

            // code 0:发送成功
            $code = $res->code();
            if ($code === 0) {
                $this->createRecord($data, $rand); // 生成验证码记录
                return $this->success('验证码发送成功！');
            } else if ($code === 33) {
                $this->error('很抱歉，为防止恶意获取验证码您每30秒只能获取1条!');
            } else if ($code === 22) {
                $this->error('很抱歉，为防止恶意获取验证码您每小时最多能获取3条!');
            } else if ($code === 17) {
                $this->error('很抱歉，为防止恶意获取验证码您在24小时内最多能获取10条!');
            } else {
                $this->error('很抱歉，获取验证码失败！');
            }

        }

    }

    /**
     * 检查参数
     */
    private function checkParam($data)
    {
        // 手机号码格式验证
        if (!isset($data['mobile']) || empty($data['mobile'])) {
            return '手机号码不能为空！';
        } else if (!preg_match('/^1(2[0-9]|3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\\d{8}$/', $data['mobile'])) {
            return '请输入正确手机号码！';
        }

        // 是否存在可绑定的手机号
        $userRes = WechatUser::where('mobile', $data['mobile'])->find();
        if (!$userRes) {
            return '不存在该用户信息，请点击游客登陆进入！';
        }elseif($userRes && $userRes['userid']) {
            return '该手机号码用户已绑定信息，请更换号码尝试！';
        }
        
        // 验证码调用时间间隔
        $smsCodeModel = new SmsCode();
        $map = [
            'mobile' => $data['mobile'],
            'status' => 0
        ];
        $res = $smsCodeModel->where($map)->order('create_time desc')->find();
        if (!empty($res)) {
            if ($res['create_time'] + $this::$INTERVAL > time()) {
                return '请在' . ($res['create_time'] + $this::$INTERVAL - time()) . '秒后再次请求！';
            }
        }
    }


    /*
     * 新建待验证记录
     */
    private function createRecord($data, $rand)
    {
        $smsCodeModel = new SmsCode();
        $smsCodeModel->data([
            'mobile' => $data['mobile'],
            'code' => $rand,
            'active_time' => time() + $this::$ACTIVETIME,
        ])->save();
    }

}